<template>
  <el-row>
    <el-col :span="24" style="padding: 24px;">
      <el-button @click="openDialog(false)" icon="Plus" type="primary">新建单位</el-button>
      <el-button icon="Refresh" @click="getList">刷新列表</el-button>
    </el-col>
  </el-row>
  <el-row>
    <el-col :span="24" style="padding:12px; min-height: 400px; height: 70vh;">
      <!-- 设置表格最大高度，超出出现滚动条 宽度自适应父容器-->
      <el-table v-loading="loading" :data="storeDataList" style="width: 50%; min-width: 400px;  height: 100%;">
        <el-table-column label="名称" align="center" prop="name"></el-table-column>
        <el-table-column label="操作" width="300" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-link :underline="false" v-if="scope.row.state != 1" style="margin-left: 24px;" type="primary"
              @click="openDialog(true, scope.row)">编辑</el-link>
            <el-link :underline="false" v-if="scope.row.state != 1" style="margin-left: 24px;" type="primary"
              @click="action(scope.row, 'del')">删除</el-link>
          </template>
        </el-table-column>
      </el-table>
    </el-col>
  </el-row>

  <div style="width: 50%; min-width: 400px; margin: 0 auto; padding: 0;">
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />
  </div>

  <!-- 新建/编辑计量单位弹窗 -->
  <el-dialog v-model="dialogVisible" :title="isEdit ? '计量单位编辑' : '新建计量单位'" width="500" draggable align-center
    :before-close="handleCloseDialog">
    <div>
      <el-form ref="invitationFormRef" label-suffix=":" :model="formData" :rules="formRules" label-width="120px"
        style="max-width: 600px">
        <!-- 计量单位（编辑时显示且不可编辑） -->
        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.name" />
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="submitForm" type="primary" :loading="submitLoading">
          提交
        </el-button>
        <el-button @click="handleCloseDialog" :disabled="submitLoading">
          取消
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import {  nextTick, } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

import { BasicUiAction } from '../../../public/engine/uiAction/basicUiAction'
import { Definition } from '../../../public/engine/common/definition'
import { DataPage } from '../../../public/network/communicationConverter'
import { createCommodityUnit, updateCommodityUnit, delCommodityUnit } from '../../../public/network/api.js';
import { Engine } from '../../../public/engine/engine.js'
import { NetworkParser } from '../../../public/network/communicationConverter.js';

export default {
  name: 'units',
  data() {
    return {
      total: 0,
      loading: false,
      queryParams: {
        pageNum: 1,
        pageSize: Definition.gDefualPageSize,
        state: null,
      },
      storeDataList: [],
      dialogVisible: false,
      isEdit: false,
      submitLoading: false,
      invitationFormRef: null,
      queryForm: null,
      formData: {
        id: '',
        name: ''
      },
      formRules: {
        invitePackageId: [
          { required: true, message: '请选择套餐', trigger: 'change' }
        ],
        monthCount: [
          { required: true, message: '请输入周期', trigger: 'blur' },
          { type: 'number', min: 1, message: '周期必须大于0', trigger: 'blur' }
        ]
      },
      basicUiAction: new BasicUiAction(),
    }
  },
  methods: {
    async getList() {
      try {
        this.loading = true
        // const res = await getInvitations(this.queryParams)
        const res = await this.basicUiAction.getCommodityUnit(new DataPage(this.queryParams.pageNum, 0, this.queryParams.pageSize))

        if (res && res.data && res.data.dataList) {
          this.storeDataList = res.data.dataList
          this.total = res.data.pageInfo.total;
        } else if (res.errorCode) {
          this.categoryLoadStatus = 'noMore'
        }
        else if (res.resErr) {
          console.error('获取列表失败', error)
          ElMessage.error('获取列表失败')
        }


      } catch (error) {
        console.error('获取列表失败', error)
        ElMessage.error('获取列表失败')
      } finally {
        this.loading = false
      }
    },
    openDialog(editMode = false, rowData = null) {
      this.isEdit = editMode
      if (editMode && rowData) {
        Object.assign(this.formData, {
          id: rowData.id,
          name: rowData.name
        })
      } else {
        this.resetForm()
      }
      this.dialogVisible = true
    },
    resetForm() {
      Object.assign(this.formData, {
        id: '',
        name: ''
      })
      if (this.$refs.invitationFormRef) {
        this.$refs.invitationFormRef.resetFields()
      }
    },
    handleCloseDialog() {
      if (!this.submitLoading) {
        this.dialogVisible = false
      }
    },
    async submitForm() {
      try {
        this.submitLoading = true
        await this.$refs.invitationFormRef.validate()

        let retData = null;
        if (this.isEdit) {
          retData = await updateCommodityUnit(this.formData.id, this.formData.name, true, Engine.profile.org.orgId);

        }
        else {
          retData = await createCommodityUnit(this.formData.name, true, Engine.profile.org.orgId);
        }

        // ApiReturnStruct
        const apiRet = NetworkParser.parseNetworkResult(retData, null);
        if (apiRet.data || apiRet.resErr == null) {
          ElMessage.success(this.isEdit ? '编辑成功' : '创建成功')
          this.dialogVisible = false;
          this.getList()

        } else {
          if (apiRet.resErr) {
            ElMessage.error((this.isEdit ? '更新失败' : '新增失败:') + apiRet.resErr)
          }
        }
      } catch (error) {
        console.error('提交失败', error)
        if (error !== 'validate') {
          ElMessage.error('提交失败')
        }
      } finally {
        this.submitLoading = false
      }
    },
    async delInvitationRecord(id) {
      try {
        await ElMessageBox.confirm('确认删除此计量单位?', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        })
        const res = await delCommodityUnit(id, Engine.profile.org.orgId)
        const apiRet = NetworkParser.parseNetworkResult(res, null);
        if (apiRet.resErr) {
          ElMessage.error('删除失败:' + apiRet.resErr);
        }
        else {
          ElMessage.success('删除成功')
          this.getList()
        }

      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败', error)
          ElMessage.error('删除失败')
        }
      }
    },
    action(data, type) {
      if (type === 'del') {
        this.delInvitationRecord(data.id)
      } else if (type === 'query') {
        this.openDialog(true, data)
      }
    },
    resetQuery() {
      this.queryParams.page = 1
      this.queryParams.state = null
      if (this.$refs.queryForm) {
        this.$refs.queryForm.resetFields()
      }
      nextTick(() => {
        this.getList()
      })
    }
  },
  mounted() {
    this.getList()
  }
}
</script>